const app = getApp()
var upload = require('../../utils/upload');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    width: 130,
    sheet: false,
    show: false,
    item_id:0,
    item: [],
    channel: [],
    cate: [],
    cate_id: 0,
    cate_name: '点击选择商品分类',
    itemImg: [],
    tempFilePaths: [],
    tempFileNum: 0
  },
  //打开载入
  onLoad: function (options) {
    if (options.scene) {
      var scene = app.util().strToArray(decodeURIComponent(options.scene));
      var id = parseInt(scene.id);
    } else {
      var id = parseInt(options.id);
    }
    //获取当前页面点击ID
    this.setData({item_id: id});
    this.getWidghHeight();
    this.getApi(id);
  },
  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    app.isLogin();
  },
  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    this.setData({
      skeleton: false,
    })
  },
  /**
   * 读取我的订单
   */
  getApi: function (id) {
    let that = this;
    if (id > 0) {
      app.api().Get("api/v1/allwin-shop-manageEdit",{id: id},function (result) {
        var imgsLen = result.data.imgs.length, imgsLen = imgsLen >= 9 ? 9 : imgsLen;
        that.setData({
          item: result.data,
          itemImg: result.data.imgs,
          tempFileNum: imgsLen,
          cate_name: result.data.cate_name,
          cate_id: result.data.category_id
        });
      })
    }
    app.api().Get('api/v1/allwin-shop-cateLits', { cate_id: 0 }, function (result) {
      that.setData({
        channel: result.data,
      }); 
    })
  },
  /**
   * 提交绑定
   */
  formSubmit: function (e) {
    let that = this;
    var data = e.detail.value;
    var isPost = false;
    var msg = '';
    if (app.util().isNull(data.name)) {
      msg = '商品名称必须填写'
    } else if (app.util().isNull(data.title)) {
      msg = '推荐描述必须填写'
    } else if (app.util().isNull(data.cost_price)) {
      msg = '成本价必须填写'
    } else if (app.util().isNull(data.sell_price)) {
      msg = '销售价必须添加'
    } else if (app.util().isNull(data.market_price)) {
      msg = '市场价必须填写'
    } else {
      isPost = true;
      wx.showLoading({ title: '提交中', mask: true })
      //商城图片并提交
      that.postFile(function (res) {
        if (res.isUpload) {
          var parms = {
            name: data.name,
            title: data.title,
            category_id: that.data.cate_id,
            cost_price: data.cost_price,
            sell_price: data.sell_price,
            market_price: data.market_price,
            imgs: that.data.itemImg,
            upload: res.filePaths
          }
          var id = that.data.item_id;
          app.api().Post('api/v1/allwin-shop-manageEdit?id='+id, parms, function (res) {
            wx.hideLoading();
            app.wxAlert(res.msg);
          })
        }
      })
    }
    if (!isPost) {
      wx.showModal({
        content: msg
      })
    }
  },
  /**
 * 获取图片宽高
 */
  getWidghHeight: function () {
    let that = this;
    const query = wx.createSelectorQuery()
    query.select('.select_img').boundingClientRect(function (res) {
      that.setData({
        width: parseInt(res.width)
      })
    }).exec();
  },
  /**
    * 图片上传
    */
  postFile: function (callback) {
    let that = this;
    var tempImg = that.data.tempFilePaths;
    var imgs = new Array();
    var count = app.util().count(tempImg);
    if (count == 0) {
      callback && callback({
        isUpload: true,
        filePaths: imgs
      });
    } else {
      var isUpload = false;
      for (var i = 0; i < count; i++) {
        upload.Upload('api/v1/allwin-store-upimg', {
          tempPath: tempImg[i]
        }, function (res) {
          if (res.code == 200) {
            imgs.push(res.data);
          } else {
            count = count - 1;
          }
          if (count == imgs.length) {
            callback && callback({
              isUpload: true,
              filePaths: imgs
            });
          }
        }, function (res) {
          console.log(res.progress);
        });
      }
    }
  },
  /**
   * 选择图片
   */
  selectImg: function () {
    let that = this;
    var tempFileNum = that.data.tempFileNum, img = that.data.tempFilePaths;
    if (tempFileNum >= 9) {
      wx.showModal({
        showCancel: false,
        content: '最多上传9张图片'
      })
    } else {
      wx.chooseImage({
        count: 1, sizeType: ['compressed'],
        success: function (res) {
          var src = res.tempFilePaths;
          var serlen = src.length;
          for (var i = 0; i < serlen; i++) {
            img.push(src[i]);
          }
          that.setData({
            tempFileNum: tempFileNum + 1,
            tempFilePaths: img,
            isUpload: false
          })
        }
      })
    }
  },
  /**
   * 删除上传图片
   */
  delUpImg: function (res) {
    let that = this;
    var array = this.data.tempFilePaths, index = res.target.id, tempFileNum = parseInt(that.data.tempFileNum);
    if (index > -1) {
      array.splice(index, 1);
      tempFileNum = tempFileNum - 1;
      if (tempFileNum < 0) {
        tempFileNum = 0;
      }
    }
    that.setData({
      tempFilePaths: array,
      tempFileNum: tempFileNum
    })
  },
  /**
   * 删除已商城图片
   */
  delImg: function (res) {
    let that = this;
    var array = this.data.itemImg, index = res.target.id, tempFileNum = parseInt(that.data.tempFileNum);
    if (index > -1) {
      array.splice(index, 1);
      tempFileNum = tempFileNum - 1;
      if (tempFileNum < 0) {
        tempFileNum = 0;
      }
    }
    that.setData({
      itemImg: array,
      tempFileNum: tempFileNum
    })
  },
  /**
   * 弹出选择二级分类
   */
  onSelect: function (e = {}) {
    let that = this;
    var cate_id = e.detail.cate_id;
    that.setData({
      sheet: !that.data.sheet,
      show: !that.data.show,
    });
    if (that.data.show){
      app.api().Get('api/v1/allwin-shop-selectCate', { cate_id: cate_id }, function (result) {
        if (200 ==result.code){
          that.setData({
            cate: result.data
          })
        }else{
          wx.showModal({
            content: result.msg,showCancel: false,
            success: function (rel) {
              that.setData({
                show: false,
                sheet: false
              });
            }
          })
        }
      })
    }
  },
  /**
   * 点击选择栏目
   */
  onClickItem({ detail = {} }) {
    this.setData({
      cate_id: detail.id,
      cate_name: detail.text,
      show: false,
      sheet:false
    });
  },
  /**
   * 打开和关闭一级分类
   */
  onSheet: function () {
    this.setData({
      sheet: !this.data.sheet,
      show:false
    });
  },
  /**
   * 打开和显示二级分类
   */
  onClose: function () {
    this.setData({
      show: !this.data.show,
      sheet: false
    });
  },
  /**
   * 点击二级栏目
   */
  onClickNav({ detail = {} }) {
    this.setData({
      mainActiveIndex: detail.index || 0
    });
  }
})